<template>
<view>

<userinfo id="user" :options="user_options" @getUserscope="getUserInfo" @toLogin="getUserInfo"></userinfo>

<view class="wrapper">
  <view class="shop-name .border-b">
    <text class="iconfont icon-dianpu"></text>
    <text>{{store_name}}</text>
  </view>

  <view class="info-box" :hidden="!card.has_card">
    <view>
      <view><lang keywords="可用余额"></lang>（{{currency}}）</view>
      <view class="num">{{card.card_info ? card.card_info.card_money : 0}}</view>
    </view>
    <view :hidden="!card.card_info">
      <view><lang keywords="会员卡号（ID）"></lang></view>
      <view class="num">{{card.card_info.card_id}}</view>
    </view>
    <view :hidden="!card.card_info">
      <view class="check" @click.stop="lookCard"><lang keywords="查看详细"></lang></view>
    </view>
    <view class="check" :hidden="card.card_info" @tap="gotoCard" :data-url="card.card_url"><lang keywords="领取会员卡"></lang></view>
  </view>

  <view class="list">
    <view class="item" v-for="(item, index) in list" :key="index" @tap="showGoodsInfo" :data-index="index">
      <view class="name">
        <view>{{item.name}}</view>
        <view class="id">{{item.number}}</view>
      </view>
      <view class="num">{{item.select_num}}</view>
      <view class="price">{{currency + item.total_money}}</view>
    </view>
  </view>

  <view class="scan-btn1" :hidden="list.length > 0" @click.stop="gotoScan">
    <image src="https://hf.pigcms.com/static/new_shop/sn_scan1.png"></image>
  </view>

  <view :class="'float-btn ' + (showMenu ? 'active' : '')">
    <view class="btn order" @tap="checkMyOrder"><lang keywords="订单"></lang></view>
    <view class="btn empty" @tap="clearCart"><lang keywords="清空"></lang></view>
    <view :style="'background:' + mobile_head_color" class="btn open" @click.stop="clickMenu">
      <lang v-if="showMenu" keywords="收起"></lang>
      <lang v-else keywords="展开"></lang>
    </view>
  </view>

  <view class="btn-box border-t">
    <view class="price-box" :style="'padding-left:' + (list.length === 0 ? '10px' : '100px')">
      <view class="num"><lang :keywords="'共' + total_num + '件'"></lang></view>
      <view class="price"><lang keywords="合计"></lang>：{{currency + total_money}}</view>
    </view>
    <button :style="'background:' + mobile_head_color" class="banlance" hover-class="banlance-hover" @tap="calculate"><lang keywords="去结算"></lang></button>
  </view>

  <view class="scan-btn2" :hidden="list.length === 0" @click.stop="gotoScan">
    <view class="circle"></view>
    <view class="icon-box">
      <text class="iconfont icon-scan"></text>
    </view>
  </view>

</view>

<!-- 商品弹窗 -->
<view class="mask" :hidden="!showGoods">
  <view class="goods-detail">
    <view class="title-box border-b">
      <view class="title">{{goods.name}}</view>
      <view>{{goods.number}}</view>
    </view>
    <view class="detail-box">
      <view class="item">
        <view><lang keywords="单价"></lang></view>
        <view class="price">{{currency + goods.price}}/{{goods.unit}}</view>
      </view>
      <view class="item">
        <view><lang keywords="数量"></lang></view>
        <view class="num-box">
          <text class="iconfont icon-jian" @tap="sub"></text>
          <text>{{goods.select_num}}</text>
          <text class="iconfont icon-jia" @tap="add"></text>
        </view>
      </view>
      <view class="item">
        <view><lang keywords="总额"></lang></view>
        <view class="price">{{currency + goods.total_money}}</view>
      </view>
    </view>
    <button hover-class="hover" @tap="deleteGoods"><lang keywords="删除"></lang></button>
    <text class="iconfont icon-cha" @tap="closeMask"></text>
  </view>
</view>

<!-- 会员卡弹窗 -->
<view class="mask" :hidden="!showCard">
  <view class="card-detail">
    <view class="title" :style="'background:' + mobile_head_color"><lang keywords="商家会员卡"></lang></view>
    <view class="detail-box">
      <view class="item border-b">
        <view>
          <view class="desc"><lang keywords="会员卡号"></lang></view>
          <view>{{card.card_info.card_id}}</view>
        </view>
        <view>
          <view class="desc"><lang keywords="实体卡号"></lang></view>
          <view>
            <text v-if="card.card_info.physical_id">{{card.card_info.physical_id}}</text>
            <lang v-else keywords="无"></lang>
          </view>
        </view>
      </view>

      <view class="item border-b"> 
        <view>
          <view class="desc"><lang keywords="会员姓名"></lang></view>
          <view>{{card.card_info.name}}</view>
        </view>
        <view>
          <view class="desc"><lang keywords="会员性别"></lang></view>
          <view>{{card.card_info.sex}}</view>
        </view>
      </view>

      <view class="item border-b"> 
        <view>
          <view class="desc"><lang keywords="手机号码"></lang></view>
          <view>{{card.card_info.phone}}</view>
        </view>
        <view>
          <view class="desc"><lang keywords="会员折扣"></lang></view>
          <view class="discount">{{card.card_info.discount}}</view>
        </view>
      </view>

      <view class="item"> 
        <view>
          <view class="desc"><lang keywords="可用积分"></lang></view>
          <view class="points">{{card.card_info.card_score}}</view>
        </view>
        <view>
          <view class="desc"><lang keywords="储值余额"></lang></view>
          <view class="price">{{currency + card.card_info.card_money}}</view>
        </view>
      </view>
      
    </view>
    <view class="close-icon">
      <text class="iconfont icon-cha" @tap="closeMask"></text>
    </view>
  </view> 
</view>

</view>
</template>

<script>
// pages/shop_new/goodsList/goodsList.js
var common = require('../../../utils/common.js');
var _this;
var app = getApp();
// 获取会员卡信息
const getShopCard = () => {
  var param = {
    store_id: _this.store_id
  };
  common.post('Shop_new&a=merchant_card', param, data => {
    if (data) {
      if (data.card_info) {
        _this.setData({
          card: data
        });

        if (data.card_info.discount == 10 || data.card_info.discount == 0) {
          common.getTxtKey('无').then(key => {
            _this.setData({
              'card.card_info.discount': key
            });
          }, () => {});
        } else {
          common.getTxtKey('X1折', {
            X1: data.card_info.discount
          }).then(key => {
            _this.setData({
              'card.card_info.discount': key
            });
          }, () => {});
        }
      }
    }
  });
};

export default {
  data() {
    return {
      mobile_head_color: '',
      showMenu: false,
      showCard: false,
      store_id: '',
      store_name: '',
      card: {},
      list: [],
      total_num: 0,
      total_money: 0,
      showGoods: false,
      goods: {},
      index: 0,
      showAuthBtn: false, // 是否显示授权登录窗口
	  currency: '¥'

    };
  },

  onShow() {
    wx.getStorage({
      key: 'scanList',
      success: res => {
        var total_num = 0;
        var total_money = 0;
        res.data = res.data.map(item => {
          total_num = total_num + item.select_num;
          item.total_money = item.select_num * item.price;
          total_money = total_money + item.total_money;
          return item;
        });

        _this.setData({
          list: res.data,
          total_num: total_num,
          total_money: total_money
        });

        console.log('购物车数据', _this.list);
      }
    });
  },

  // 生命周期函数--监听页面加载
  onLoad(options) {
    _this = this;
    common.setMainColor(_this);

    _this.setData({
      store_id: options.store_id,
      store_name: options.store_name
    });

    wx.setNavigationBarTitle({
      title: common.changeTxt('扫码购物')
    });
    getShopCard();
	common.changeCurrency(this)
  },
  methods: {
    // 点击“展开”
    clickMenu() {
      _this.setData({
        showMenu: !_this.showMenu
      });
    },

    // 查看会员卡
    lookCard() {
      _this.setData({
        showCard: true
      });
    },

    // 关闭会员卡弹窗                                                                                
    closeMask() {
      _this.setData({
        showCard: false,
        showGoods: false
      });
    },

    // 返回扫码页面
    gotoScan() {
      wx.navigateBack({
        delta: 1
      });
    },

    // 领取会员卡
    gotoCard(e) {
      // var pageTitle = e.currentTarget.dataset.url_title;
      // if (!pageTitle) {
      //   pageTitle = '';
      // }
      common.parseUrl(e.currentTarget.dataset.url, 'shop', false);
    },

    // 查看订单
    checkMyOrder() {
      common.parseUrl('url/My/shop_order_list', 'shop', false);
    },

    // 点击清空
    clearCart() {
      if (_this.list.length > 0) {
        common.getTxtKey('提示').then(key1 => {
          common.getTxtKey('您确定要清空购物车？').then(key2 => {
            wx.showModal({
              title: key1,
              content: key2,
              success: res => {
                if (res.confirm) {
                  wx.removeStorage({
                    key: 'scanList'
                  });

                  _this.setData({
                    list: [],
                    total_num: 0,
                    total_money: 0
                  });
                }
              }
            });
          }, () => {});
        }, () => {});
      }
    },

    // 点击出现商品信息弹窗
    showGoodsInfo(e) {
      var index = e.currentTarget.dataset.index;
      _this.goods = _this.list[index];

      _this.setData({
        goods: _this.goods,
        showGoods: true,
        index: index
      });
    },

    // 减
    sub() {
      if (_this.goods.select_num > 1) {
        _this.total_num--;
        _this.total_money = _this.total_money - _this.goods.price;
        _this.list[_this.index].select_num--;
        _this.list[_this.index].total_money = _this.list[_this.index].total_money - _this.goods.price;

        _this.setData({
          goods: _this.list[_this.index],
          total_num: _this.total_num,
          total_money: _this.total_money,
          list: _this.list
        });

        wx.setStorage({
          key: 'scanList',
          data: _this.list
        });
      } else {
        common.getTxtKey('已减至最少数量！').then(key => {
          wx.showToast({
            title: key,
            icon: 'none',
            duration: 2000
          });
        }, () => {});
      }
    },

    // 加
    add() {
      console.log('_this.goods', _this.goods);
      _this.total_num++;
      _this.total_money = _this.total_money + _this.goods.price;
      _this.list[_this.index].select_num++;
      _this.list[_this.index].total_money = _this.list[_this.index].total_money + _this.goods.price;

      _this.setData({
        goods: _this.list[_this.index],
        total_num: _this.total_num,
        total_money: _this.total_money,
        list: _this.list
      });

      wx.setStorage({
        key: 'scanList',
        data: _this.list
      });
    },

    // 删除
    deleteGoods() {
      common.getTxtKey('提示').then(key1 => {
        common.getTxtKey('确定删除该商品？').then(key2 => {
          wx.showModal({
            title: key1,
            content: key2,
            success: res => {
              if (res.confirm) {
                _this.list = _this.list.filter(item => item.goods_id != _this.goods.goods_id);
                _this.total_num = _this.total_num - _this.goods.select_num;
                _this.total_money = _this.total_money - _this.goods.total_money;

                _this.setData({
                  list: _this.list,
                  total_num: _this.total_num,
                  total_money: _this.total_money,
                  goods: {},
                  showGoods: false
                });

                wx.setStorage({
                  key: 'scanList',
                  data: _this.list
                });
              }
            }
          });
        }, () => {});
      }, () => {});
    },

    // 点击结算
    calculate() { 
      if (_this.list.length > 0) {
        var list = _this.list;
        var arr = [];

        for (let i = 0; i < list.length; i++) {
          arr[i] = {};
          arr[i].productId = list[i].goods_id_real;
          arr[i].productName = list[i].name;
          arr[i].productPrice = list[i].price;
          arr[i].count = list[i].select_num;
          arr[i].productParam = list[i].spec_arr;
        }

        wx.setStorage({
          key: 'shop_cart_' + _this.store_id,
          data: JSON.stringify(arr),

          success() {
            var ticket = wx.getStorageSync('ticket');

            if (ticket) {
              wx.navigateTo({
                url: `/pages/shop_new/confirmOrder/newCart?store_id=${_this.store_id}&shop_scan=1`
              });
            } else {
              _this.setData({
                toLogin: true
              });
            }
          }

        });
      }
    },

    getUserInfo(e) {
      if (e.detail.getUserInfo) {
        wx.navigateTo({
          url: `/pages/shop_new/confirmOrder/newCart?store_id=${_this.store_id}&shop_scan=1`
        });
      }
    },

    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>

.border-t{position: relative;}
.border-b::after{content: '';position: absolute;bottom: 0;left: 0;height: 1rpx;width: 100%;background: #e5e5e5;transform: scaleY(0.5);}
.border-t::after{content: '';position: absolute;top: 0;left: 0;height: 1rpx;width: 100%;background: #e5e5e5;transform: scaleY(0.5);}


.wrapper{width: 100%;padding-bottom: 120px;overflow-x: hidden;}

.shop-name{background: #fff;padding:20px 10px;font-size: 16px;color: #333;position: relative;}
.shop-name .icon-dianpu{color: #06c1ae;margin-right: 5px;}
.shop-name.border-b::after{left: 10px;}

.info-box{padding: 20px 10px;background: #fff;display: flex;justify-content: space-between;font-size: 14px;color: #888;}
.info-box .num{color: #333;margin-top: 5px;}
.info-box .check{color: #06c1ae;line-height: 43px;}

.list{margin-top: 10px;}
.list .item{display: flex;justify-content: space-between;align-items: center;padding: 10px 10px;font-size: 14px;color: #333;}
.list .item:nth-child(odd){background: #fff;}
.list .item .price{color: #e93e14;}
.list .item .name .id{color: #666;}


.scan-btn1{text-align: center;margin-top: 50px;}
.scan-btn1 image{width: 160px;height: 160px;}

.float-btn{position: fixed;bottom: 60px;right: 10px;}
.float-btn .btn{width: 50px;height: 50px;border-radius: 50%;color: #fff;line-height: 50px;text-align: center;font-size: 14px;margin-top: 15px;}
.float-btn .open{background: #06c1ae;box-shadow: 0 0 20px 5px #c9f7f3;}
.float-btn .order{background: #ff5f45;box-shadow: 0 0 20px 5px #fad8d2;}
.float-btn .empty{background: #c1c1c1;box-shadow: 0 0 20px 5px #e7e6e6;}
.float-btn .order, .float-btn .empty{transform: scale(0);transition: all 0.3s;opacity: 0;}
.float-btn.active .order, .float-btn.active .empty{transform: scale(1);opacity: 1;}

button::after{border: none;}
.btn-box{position: fixed;bottom: 0;left: 0;right: 0;display: flex;z-index: 2;}
.btn-box button{background: #fb4e44;border-radius: 0;color: #fff;font-size: 16px;height: 50px;line-height: 50px;}
.btn-box .price-box{background: #fff;flex: 3;display: flex;align-items: center;justify-content: space-between;padding: 0 10px 0 100px;}
.btn-box .price-box .num{color: #999;font-size: 14px;}
.btn-box .price-box .price{color: #e93e14;font-size: 16px;}
.btn-box .banlance{flex:1;background: #06c1ae;}
.btn-box .banlance-hover{background: #05a796;}

.scan-btn2 .circle{width: 80px;height: 80px;border: 1rpx solid #ddd;border-radius: 50%;position: fixed;bottom: 
10px;left: 10px;z-index: 1;background: #fff;box-sizing: border-box;}
.scan-btn2 .icon-box{width: 70px;height: 70px;border-radius: 50%;position: fixed;bottom:15px;left: 15px;z-index: 3;background: linear-gradient(#48e35a, #06c1ad);text-align: center;line-height: 70px;color: #fff;}
.scan-btn2 .icon-box .icon-scan{font-size: 40px;}

.mask{position: fixed;top: 0;left: 0;right: 0;bottom: 0;background: rgba(0, 0, 0, 0.5);z-index: 4;}

.goods-detail, .card-detail{width: 85%;background: #fff;border-radius: 2px;overflow: hidden;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);}
.goods-detail .title-box{padding: 20px 10px;position: relative;font-size: 14px;color: #999;}
.goods-detail .title-box .title{font-size: 16px;color: #333;margin-bottom: 10px;}
.goods-detail .detail-box{padding: 10px;}
.goods-detail .detail-box .item{display: flex;justify-content: space-between;align-items: center;padding: 10px 0;font-size: 14px;color: #333;}
.goods-detail .detail-box .item .price{color: #e93e14;}
.goods-detail .detail-box .item .num-box{display:flex;align-items: center;}
.goods-detail .detail-box .item .num-box text{margin-left: 10px;}
.goods-detail .detail-box .item .num-box .iconfont{font-size: 26px;color: #06c1ae;}
.goods-detail button{background: #06c1ae;color: #fff;border-radius: 0 0 2px 2px;font-size: 16px;line-height: 3;}
.goods-detail button.hover{background: #05a796;}
.goods-detail .icon-cha{position: absolute;top: 0px;right: 0px;font-size: 26px;color: #999;padding: 10px;}

.card-detail{border-radius: 5px 5px 0 0;background: transparent;}
.card-detail .title{font-size: 18px;color: #fff;background: #06c1ae;text-align: center;padding: 12px 0;}
.card-detail .detail-box{padding: 15px 20px;background: #fff;border-radius: 0 0 5px 5px;}
.card-detail .detail-box .item{display: flex;justify-content: space-between;padding: 10px 0;position: relative;font-size: 16px;color: #333;}
.card-detail .detail-box .item>view:first-child{flex: 2;}
.card-detail .detail-box .item>view:last-child{flex: 1;}
.card-detail .detail-box .item .desc{color: #999;font-size: 14px;margin-bottom: 5px;}
.card-detail .detail-box .item .discount{color: #06c1ae;}
.card-detail .detail-box .item .points{color: #e93e14}
.card-detail .detail-box .item .price{color: #ff9100}
.card-detail .close-icon{text-align: center;color: #fff;margin-top: 20px;}
.card-detail .close-icon .icon-cha{font-size: 32px;}

</style>